<template>
    <div v-if="!readonly" class="">
        <el-select class="ybs-select" v-if="type == 'select'" popper-append-to-body filterable :clearable="clearable"
            v-model="itemValue" :size="size" :multiple="realMultiple" :placeholder="placeholder" :disabled="disabled">
            <el-option :label="v.name" :value="v.value" v-for="(v, i) in dictList" :key="i"></el-option>
        </el-select>

        <vxe-checkbox-group v-if="type == 'checkbox'" v-model="itemValue" :size="size" :disabled="disabled">
            <vxe-checkbox :label="v.value" v-for="(v, i) in dictList" :key="i" :content="v.name"></vxe-checkbox>
        </vxe-checkbox-group>

        <vxe-radio-group v-if="type == 'radio'" v-model="itemValue" :size="size" :disabled="disabled">
            <vxe-radio :label="v.value" v-for="(v, i) in dictList" :key="i" :content="v.name"></vxe-radio>
        </vxe-radio-group>
    </div>
    <!-- 只读 -->
    <div v-else>
        {{ itemName }}
    </div>
</template>

<script>
import { getDict } from '@/api/public'
import { cloneDeep } from "@/utils";
export default {
    model: {
        prop: "value",
        event: "input"
    },
    props: {
        // 绑定值
        value: [String, Number, Array],
        // 多选
        multiple: Boolean,
        // 表单数据
        data: Object,
        // 字典Code
        dictCode: String,
        // 清除按钮
        clearable: {
            type: Boolean,
            default: true,
        },
        // 提示
        placeholder: {
            type: String,
            default: '请选择'
        },
        // 禁用
        disabled: Boolean,
        // 只读
        readonly: Boolean,
        // 尺寸
        size: String,
        bounds: [String, Object], // 额外绑定的字段
        // 初始化数据 - 异步
        initData: Function,
        // 初始化数据 - 同步
        dataList: Array,
        // 类型
        type: {
            type: String,
            default: 'select'  // select | checkbox | radio
        }
    },
    data() {
        return {
            dictList: [],
            dictInfo: {},
        }
    },
    computed: {
        realMultiple: {
            get() {
                if (this.multiple) {
                    return true;
                } else {
                    if (this.type === 'checkbox') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
        itemValue: {
            get() {
                return this.value;
            },
            /**
             * 设置选中项
             * @param {Array|String} e - 选中的值或值的数组
            */
            set(e) {
                let find = {};
                // 当bounds属性存在时，处理表单数据更新
                if (this.bounds) {
                    // 如果是多选
                    if (this.realMultiple) {
                        if (typeof (this.bounds) == 'string') {
                            // 如果bounds是字符串，直接更新对应的表单数据
                            const boundsValue = this.dictList.filter(d => e.find(field => field === d.value)).map(d => d.name)
                            this.$set(this.formData, [this.bounds], boundsValue)
                        }
                        if (typeof (this.bounds) == 'object') {
                            // 如果bounds是对象，根据其键值更新对应的表单数据

                            Object.keys(this.bounds).forEach(key => {
                                if (e) {
                                    const boundsValue = this.dictList.filter(d => e.find(field => field === d.value)).map(d => d.details[[this.bounds[key]]])
                                    this.$set(this.formData, key, boundsValue)
                                } else {
                                    this.$set(this.formData, key, null)
                                }
                            })
                        }
                    } else {
                        // 如果不是多选，根据bounds类型更新表单数据
                        if (typeof (this.bounds) == 'string') {
                            // 如果bounds是字符串，直接更新对应的表单数据
                            this.$set(this.formData, [this.bounds], this.dictList.find(d => d.value === e)?.name)
                        }
                        if (typeof (this.bounds) == 'object') {
                            // 如果bounds是对象，根据其键值更新对应的表单数据
                            Object.keys(this.bounds).forEach(key => {
                                if (e) {
                                    this.$set(this.formData, key, this.dictList.find(d => d.value === e).details[[this.bounds[key]]])
                                } else {
                                    this.$set(this.formData, key, null)
                                }
                            })
                        }
                    }
                }

                let res = this.dictList.find(d => d.value === e)
                if (this.realMultiple && e) {
                    res = this.dictList.filter(d => e.find(field => field === d.value))
                }
                this.$emit('change', e, res)
                this.$emit('input', e)
            }
        },
        formData: {
            get() {
                return this.data;
            },
            set(e) {
                this.$emit('update:data', e)
            }
        },
        itemName() {
            // 使用可选操作符防止undefined错误
            if (this.realMultiple) {
                const res = this.dictList.filter(d => this.itemValue.includes(d.value)).map(d => d.name)
                return res.join('、')
            } else {
                return this.dictList.find(d => d.value === this.itemValue)?.name || ''
            }
        }
    },

    created() {
    },
    mounted() {
        this.init()
    },
    methods: {
        init() {

            try {
                if (Array.isArray(this.dataList) && this.dataList.length > 0) {
                    this.dictList = this.dataList;
                    this.itemValue = this.value;
                    return;
                }

                if (typeof this.initData === 'function') {
                    this.initData(cloneDeep(this.formData)).then(res => {
                        this.dictList = res;
                        this.itemValue = this.value;

                    }).catch(error => {
                        console.error('Error in initData:', error);
                    });
                    return;
                }

                if (this.dictCode) {
                    getDict(this.dictCode).then(res => {
                        this.dictList = res.dictList;
                        this.itemValue = this.value;
                        this.dictInfo = res.dictInfo;
                    }).catch(error => {
                        console.error('Error in getDict:', error);
                    });
                    return;
                }
            } catch (error) {
                console.error('Unexpected error in init:', error);
            }
        },
    },
}
</script>

<style lang="scss" scoped></style>
